Scroll Progress Bar

For Loop

The for-loop is a control structure used to repeat a block of code for a specified number of iterations. It consists of three parts: initialization, condition, and update. The loop starts with the initialization step, followedby the condition check. If the condition is true, the code inside the loop is executed, and then the update step is performed. The loop continues as long as the condition remains true.

Syntax:

for (initialization; condition; update) {
    // Code to be repeated
}
Program:

In this program, use a for loop to print the numbers from 1 to 5, each on a new line.


#include <stdio.h>

int main() {
    // Initialization: Set the loop control variable 'i' to 1
    // Condition: The loop will continue as long as 'i' is less than or equal to 5
    // Update: Increment 'i' by 1 after each iteration
    for (int i = 1; i <= 5; i++) {
        printf("%d\n", i); // Print the value of 'i' on a new line
    }

    return 0;
}
  • Start by initializing the loop control variable i to 1 using int i = 1;.
  • Next, have the condition i <= 5, which will be checked before each iteration. If the condition is true, the loop will continue; otherwise, it will terminate.
  • Inside the loop, print the value of i using printf("%d\n", i);. This will display the value of i on a new line.
  • After each iteration, the update step i++ is executed, which increments the value of i by 1.
  • The loop will continue executing as long as the condition i <= 5 remains true. Once i becomes 6, the condition will be false, and the loop will terminate.
Output:

1
2
3
4
5

In the output, can see that the loop has printed the numbers from 1 to 5, each on a new line, as specified by the for loop's initialization, condition, and update.


What is a for-loop in C?


Iteration

What is the initialization part of a for-loop responsible for?


Setup

What does the condition part of a for-loop determine?


Termination

What is the role of the increment part in a for-loop?


Change

What is the primary purpose of using a for-loop in C?


Repetition